package jwt

import (
	"apiManageGo/src/core/common/config"
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type UserClaims struct {
	jwt.RegisteredClaims
	// 声明你自己的要放进去 token 里面的数据
	UserId       string
	RefreshToken string
}
type RefreshTokenClaims struct {
	jwt.RegisteredClaims
	UserId string
}

func (u *UserClaims) CreateToken() (token_return string, refresh_token_return string, err error) {
	//设置过期时间
	expirationTime := time.Now().Add(config.GetConfig().Jwt.Expire * time.Hour)
	u.RegisteredClaims = jwt.RegisteredClaims{
		ExpiresAt: jwt.NewNumericDate(expirationTime),
		IssuedAt:  jwt.NewNumericDate(time.Now()),
		NotBefore: jwt.NewNumericDate(time.Now()),
	}
	//生产一个token
	token := jwt.NewWithClaims(jwt.SigningMethodHS512, u)
	//签名
	tokenStr, err := token.SignedString([]byte(config.GetConfig().Jwt.Secret))
	tokenReturn, err := createRefreshToken(u.UserId)
	return tokenStr, tokenReturn, err
}

func createRefreshToken(userId string) (refresh_token_return string, err error) {
	refreshTokenClaims := &RefreshTokenClaims{
		UserId: userId,
	}
	//生产一个token
	token := jwt.NewWithClaims(jwt.SigningMethodHS512, refreshTokenClaims)
	//签名
	tokenStr, err := token.SignedString([]byte(config.GetConfig().Jwt.RefreshTokenKey))
	if err == nil {
		return tokenStr, nil
	}
	return "", err
}

func CheckToken(tokenStr string) (*UserClaims, error) {
	claims := &UserClaims{}
	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.GetConfig().Jwt.Secret), nil
	})
	if err != nil {
		return nil, err
	} else {
		if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
			return claims, nil
		}
	}
	return nil, errors.New("token is invalid")
}
